﻿using System;
using System.ComponentModel;
using System.IO.IsolatedStorage;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using SC2TV.Object;
using SC2TV.ViewModel;

namespace SC2TV
{
    public partial class ClientPage
    {
        public ClientPage()
        {
            InitializeComponent();
            BackKeyPress += (sender, args) => Application.Current.Terminate();
        }

        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            if (DesignerProperties.IsInDesignTool) return;

            var vm = DataContext as ClientViewModel;
            await vm.Load();
        }

        private void StreamSelected(object sender, SelectionChangedEventArgs e)
        {
            var lls = sender as LongListSelector;
            if(lls.SelectedItem == null) return;

            if (e.AddedItems.Count > 0)
            {
                var stream = e.AddedItems[0] as StreamTile;
                if (stream == null) return;
                NavigationService.Navigate(new Uri("/StreamPage.xaml?channelName=" + stream.Title + "&stream=" + String.Concat("http://sc2tv.ru",stream.ChannelUri), UriKind.Relative));
            }

            lls.SelectedItem = null;
        }

        private void LogoutClick(object sender, EventArgs e)
        {
            IsolatedStorageSettings.ApplicationSettings.Clear();
            NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
        }

        private void PrivateMessageClick(object sender, SelectionChangedEventArgs e)
        {
            var lls = sender as LongListSelector;
            if(lls.SelectedItem == null) return;
            var privateMessage = lls.SelectedItem as PrivateMessageIn;
            var vm = DataContext as ClientViewModel;
            if(privateMessage == null || vm == null) return;

            NavigationService.Navigate(new Uri("/PrivateMessageReaderPage.xaml?messageUrl=http://sc2tv.ru" + privateMessage.MessageUrl, UriKind.Relative));
            lls.SelectedItem = null;
        }

        private void AboutClick(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/AboutPage.xaml", UriKind.Relative));
        }
    }
}